<template>
  <div class="ai-assistant-page">
    <el-row :gutter="0" class="full-height">
      <el-col :span="6" class="conversation-list-col">
        <conversation-list 
          :active-id="conversationId" 
          @select-conversation="navigateToConversation"
        />
      </el-col>
      <el-col :span="18" class="chat-box-col">
        <chat-box 
          :conversation-id="conversationId"
          :title="conversationTitle"
          @conversation-created="onConversationCreated"
          @conversation-deleted="onConversationDeleted"
          @title-updated="onTitleUpdated"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import ChatBox from '@/components/ai/ChatBox.vue';
import ConversationList from '@/components/ai/ConversationList.vue';
import aiService from '@/services/aiService';

export default {
  name: 'AiAssistant',
  components: {
    ChatBox,
    ConversationList
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const conversationTitle = ref('');
    
    // 从路由获取对话ID
    const conversationId = computed(() => route.params.id || null);
    
    // 加载对话信息
    const loadConversationInfo = async () => {
      if (!conversationId.value) {
        conversationTitle.value = '';
        return;
      }
      
      try {
        const response = await aiService.getConversationMessages(conversationId.value);
        // 获取对话的第一条消息作为标题
        if (response.data.data.length > 0) {
          const firstMessage = response.data.data[0];
          conversationTitle.value = firstMessage.content.substring(0, 30) + 
                                   (firstMessage.content.length > 30 ? '...' : '');
        }
      } catch (error) {
        console.error('加载对话信息错误:', error);
      }
    };
    
    // 导航到特定对话
    const navigateToConversation = (id) => {
      router.push(`/ai-assistant/${id}`);
    };
    
    // 创建新对话的回调
    const onConversationCreated = (id) => {
      router.push(`/ai-assistant/${id}`);
    };
    
    // 删除对话的回调
    const onConversationDeleted = () => {
      router.push('/ai-assistant');
    };
    
    // 更新标题的回调
    const onTitleUpdated = (newTitle) => {
      conversationTitle.value = newTitle;
    };
    
    onMounted(() => {
      if (conversationId.value) {
        loadConversationInfo();
      }
    });
    
    return {
      conversationId,
      conversationTitle,
      navigateToConversation,
      onConversationCreated,
      onConversationDeleted,
      onTitleUpdated
    };
  }
};
</script>

<style scoped>
.ai-assistant-page {
  height: calc(100vh - 100px); /* 减去顶部导航栏的高度 */
}

.full-height {
  height: 100%;
}

.conversation-list-col, .chat-box-col {
  height: 100%;
}

@media (max-width: 768px) {
  .conversation-list-col {
    display: none;
  }
  
  .chat-box-col {
    width: 100%;
  }
}
</style> 